<template>
	<div>
		<el-icon @click="drawer = !drawer" size="82">
			<icon-file-pdf-one theme="filled" size="128" fill="#0975f5" :strokeWidth="1" strokeLinejoin="bevel" strokeLinecap="square" />
		</el-icon>
		<el-drawer v-model="drawer" title="文件预览" size="60%" append-to-body>
			<PDF
				:src="imgUrl"
				@onComplete="onComplete"
				v-loading="loading"
				element-loading-text="初始化数据中..."
				element-loading-svg-view-box="-10, -10, 50, 50"
				element-loading-background="rgba(122, 122, 122, 0.4)"
			/>
		</el-drawer>
	</div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import defaultFile from '@/assets/icons/defaultFile.png'
import PDF from 'pdf-vue3'
import { DowloadPreviewImage } from '@/utils/util'

export default defineComponent({
	components: {
		PDF,
	},
	props: {
		src: {
			type: String,
		},
		baseStyle: {
			type: Object,
			default: () => ({
				width: '100%',
				height: '100%',
			}),
		},
	},
	emits: ['download'],
	setup(props, { emit }) {
		const drawer = ref(false)
		const loading = ref(false)

		const onComplete = () => {
			loading.value = false
		}

		const imgUrl = ref('') as any
		const fileName = ref(props.src?.slice(-12))
		const getPreviewImage = async () => {
			if (props.src?.includes('ningxiang')) {
				const blobUrl = (await DowloadPreviewImage(props.src, 'blob')) as string
				const blobToDataURL = (blob) => {
					return new Promise((resolve, reject) => {
						const reader = new FileReader()
						reader.readAsDataURL(blob)
						reader.onload = () => resolve(reader.result)
						reader.onerror = (error) => reject(error)
					})
				}
				const url = await blobToDataURL(blobUrl)
				imgUrl.value = url
			} else {
				imgUrl.value = props.src
			}
		}
		watch(
			() => props.src,
			() => {
				getPreviewImage()
			},
			{
				immediate: true,
			}
		)

		onMounted(() => {
			loading.value = true
		})
		return {
			drawer,
			loading,
			defaultFile,
			onComplete,
			imgUrl,
			fileName,
		}
	},
})
</script>

<style scoped lang="scss">
.preview-img-box {
	width: 128px;
	height: 128px;
	position: relative;
	.el-image {
		img {
			width: 100%;
			height: 100%;
		}
	}
}
</style>
